import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
// 重写了原型上的push方法，统一的处理了错误信息
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/admin',
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/components/Login/index.vue')
  },
  {
    path: '/welcome',
    name: 'Welcome',
    redirect: '/addArticle',
    component: () => import('@/components/Admin/index.vue'),
    children: [
      {
        path: '/addArticle',
        name: 'AddArticle',
        component: () => import('@/components/AddArticle/index.vue'),
      },
      {
        path: '/articleList',
        name: 'ArticleList',
        component: () => import('@/components/ArticleList/index.vue'),
      },
      {
        path: '/updateArticle/:id',
        name: 'UpdateArticle',
        component: () => import('@/components/AddArticle/index.vue'),
      },
      {
        path: '/message',
        name: 'Message',
        component: () => import('@/components/Message/index.vue'),
      },
      {
        path: '/essay',
        name: 'Essay',
        component: () => import('@/components/Essay/index.vue'),
      },
    ]
  }
]


const router = new VueRouter({
  base:'/',
  mode: "hash",
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path == '/admin') {
    return next();
  } else {
    let token = window.localStorage.getItem('token');
    if (!token) {
      return next({
        path:'/'
      });
    } else {
      return next();
    }
  }
})

export default router
